//
//  BMHHTTPSession.m
//  BeautyVideos
//
//  Created by 爆米花 on 16/10/12.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "BMHHTTPSession.h"
#import "BMHAppClient.h"
#import "UIImageView+WebCache.h"
//#import <UIApplication+YYAdd.h>

@implementation BMHHTTPSession


#pragma mark - GET
+ (nullable NSURLSessionDataTask *)GET:(nonnull NSString *)urlString
                             paraments:(nullable id)paraments
                         completeBlock:(nullable completeBlock)completeBlock
{
    return [[BMHAppClient sharedClient] GET:urlString
                                 parameters:paraments
                                   progress:^(NSProgress * _Nonnull downloadProgress) {
                                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                       completeBlock(dict,nil);
                                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                       completeBlock(nil,error);
                                   }];
}



+(nullable NSURLSessionDataTask *)GET:(nonnull NSString *)urlstring
                            paraments:(nullable id)paraments
                              success:(nullable HttpSuccessBlock)success
                              failure:(nullable HttpFailureBlock)failure
{
    return [[BMHAppClient sharedClient] GET:urlstring
                                 parameters:paraments
                                   progress:^(NSProgress * _Nonnull downloadProgress) {
                                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                       success(responseObject);
                                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                       failure(error);
                                   }];
    
    
}

+(nullable NSURLSessionDataTask *)GETKK:(nonnull NSString *)urlstring
                              paraments:(nullable id)paraments
                                success:(nullable HttpSuccessBlock)success
                                failure:(nullable HttpFailureBlock)failure
{
    return [[BMHAppClient sharedClientKK] GET:urlstring
                                 parameters:paraments
                                   progress:^(NSProgress * _Nonnull downloadProgress) {
                                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                       //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                       success(responseObject);
                                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                       failure(error);
                                   }];
    
    
}



+(nullable NSURLSessionDataTask *)TMGET:(nonnull NSString *)urlstring
                              paraments:(nullable id)paraments
                                success:(nullable HttpSuccessBlock)success
                                failure:(nullable HttpFailureBlock)failure;
{
    return [[BMHAppClient sharedClientTMLogin] GET:urlstring
                                        parameters:paraments
                                          progress:^(NSProgress * _Nonnull downloadProgress) {
                                          } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                              //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                              success(responseObject);
                                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                              failure(error);
                                          }];

    
}

+(nullable NSURLSessionDataTask *)GETTEST:(nonnull NSString *)urlstring
                                paraments:(nullable id)paraments
                                  success:(nullable HttpSuccessBlock)success
                                  failure:(nullable HttpFailureBlock)failure
{
    return [[BMHAppClient  sharedTest] GET:urlstring
                                   parameters:paraments
                                     progress:^(NSProgress * _Nonnull downloadProgress) {
                                     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                         //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                         success(responseObject);
                                     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                         failure(error);
                                     }];
    
    
}


+(nullable NSURLSessionDataTask *)GETBMHVideo:(nonnull NSString *)urlstring
                                        paraments:(nullable id)paraments
                                          success:(nullable HttpSuccessBlock)success
                                          failure:(nullable HttpFailureBlock)failure
{
    return [[BMHAppClient  bmhVide] GET:urlstring
                                  parameters:paraments
                                    progress:^(NSProgress * _Nonnull downloadProgress) {
                                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                        //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                        success(responseObject);
                                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                        failure(error);
                                    }];
    
    
}

+(nullable NSURLSessionDataTask *)GETBMHVideoTEST:(nonnull NSString *)urlstring
                                paraments:(nullable id)paraments
                                  success:(nullable HttpSuccessBlock)success
                                  failure:(nullable HttpFailureBlock)failure
{
    return [[BMHAppClient  bmhVideoTest] GET:urlstring
                                parameters:paraments
                                  progress:^(NSProgress * _Nonnull downloadProgress) {
                                  } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                      //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                      success(responseObject);
                                  } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                      failure(error);
                                  }];
    
    
}



+(nullable NSURLSessionDataTask *)UploadHeadGET:(nonnull NSString *)urlstring
                                      paraments:(nullable id)paraments
                                        success:(nullable HttpSuccessBlock)success
                                        failure:(nullable HttpFailureBlock)failure;
{
    return [[BMHAppClient sharedClientPicture] GET:urlstring
                                 parameters:paraments
                                   progress:^(NSProgress * _Nonnull downloadProgress) {
                                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                       //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                       success(responseObject);
                                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                       failure(error);
                                   }];
    
    
}



#pragma mark - POST
+ (nullable NSURLSessionDataTask *)POST:(nonnull NSString *)urlString
                              paraments:(nullable id)paraments
                          completeBlock:(nullable completeBlock)completeBlock
{
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误
    
    [BMHAppClient sharedClient].requestSerializer = [AFJSONRequestSerializer serializer];//请求
    [BMHAppClient sharedClient].responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    
    // post请求
    return [[BMHAppClient sharedClient] POST:urlString
                                  parameters:paraments
                   constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                       // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
                   } progress:^(NSProgress * _Nonnull uploadProgress){
                   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                       NSLog(@"%@", responseObject);
                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                       NSLog(@"dict start ----\n%@   \n ---- end  -- ", dict);
                       // 请求成功，解析数据
                       completeBlock(dict,nil);
                   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                       NSLog(@"%@", [error localizedDescription]);
                       // 请求失败
                       completeBlock(nil,error);
                   }];
    
}



+ (nullable NSURLSessionDataTask *)POST:(nonnull NSString *)urlString
                              secretKey:(nonnull NSString *)secretKey
                              paraments:(nullable id)paraments
                                success:(nullable HttpSuccessBlock)success
                                failure:(nullable HttpFailureBlock)failure
{
    
    [BMHAppClient sharedPostZHIFU].requestSerializer = [AFJSONRequestSerializer serializer];//请求
    [BMHAppClient sharedPostZHIFU].responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    
    [[BMHAppClient sharedPostZHIFU].requestSerializer setValue:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] forHTTPHeaderField:@"versions"];
    
    [[BMHAppClient sharedPostZHIFU].requestSerializer setValue:secretKey ?: @"" forHTTPHeaderField:@"sign"];
    
    return [[BMHAppClient sharedPostZHIFU] POST:urlString parameters:paraments progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"dict start ----\n%@   \n ---- end  -- ", dict);
        success(dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
        failure(error);
    }];
    
    
}
#pragma mark - 上传头像
+(NSURLSessionDataTask *)UploadHeadPOST:(NSString *)urlString paraments:(id)paraments pictures:(NSArray *)pics completeBlock:(completeBlock)completeBlock
{
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误
    
    [BMHAppClient sharedClientPicture].requestSerializer = [AFJSONRequestSerializer serializer];//请求
    [BMHAppClient sharedClientPicture].responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    
    // post请求
    return [[BMHAppClient sharedClientPicture] POST:urlString
                                         parameters:paraments
                          constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                              // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
                              
                              for (int i = 0; i<pics.count; i++) {
                                  NSData *data = UIImagePNGRepresentation(pics[i]);
                                  
                                  [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"pic%d", i] fileName:@"image.jpg" mimeType:@"image/png"];
                              }
                              
                          } progress:^(NSProgress * _Nonnull uploadProgress){
                          } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                              NSLog(@"%@", responseObject);
                              NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                              NSLog(@"dict start ----\n%@   \n ---- end  -- ", dict);
                              // 请求成功，解析数据
                              completeBlock(dict,nil);
                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                              NSLog(@"%@", [error localizedDescription]);
                              // 请求失败
                              completeBlock(nil,error);
                          }];
    
    
    
}



+ (nullable NSURLSessionDataTask *)UploadHeadPOST:(nonnull NSString *)urlString
                                        paraments:(nullable id)paraments
                                         pictures:(nullable NSArray *)pics
                                          success:(nullable HttpSuccessBlock)success
                                          failure:(nullable HttpFailureBlock)failure
{
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误
    
    [BMHAppClient sharedClientPicture].requestSerializer = [AFJSONRequestSerializer serializer];//请求
    [BMHAppClient sharedClientPicture].responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    
    // post请求
    return [[BMHAppClient sharedClientPicture] POST:urlString
                                         parameters:paraments
                          constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                              // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
                              
                              for (int i = 0; i<pics.count; i++) {
                                  NSData *data = UIImagePNGRepresentation(pics[i]);
                                  
                                  [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"pic%d", i] fileName:@"image.jpg" mimeType:@"image/png"];
                              }
                              
                          } progress:^(NSProgress * _Nonnull uploadProgress){
                          } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                              NSLog(@"%@", responseObject);
//                              NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//                              NSLog(@"dict start ----\n%@   \n ---- end  -- ", dict);
                              // 请求成功，解析数据
                              success(responseObject);
                          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                              NSLog(@"%@", [error localizedDescription]);
                              // 请求失败
                              failure(error);
                          }];
    
    
}

//猜拳游戏
+ (nullable NSURLSessionDataTask *)getWithGamePath:(nonnull NSString *)path
                                            params:(nullable NSDictionary *)params
                                           success:(nullable HttpSuccessBlock)success
                                           failure:(nullable HttpFailureBlock)failure
{
    return [[BMHAppClient sharedClientGame] GET:path
                                     parameters:params
                                       progress:^(NSProgress * _Nonnull downloadProgress) {
                                       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                           //                                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                           if (responseObject == nil) {
                                               return ;
                                           }
                                           success(responseObject);
                                       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                           failure(error);
                                       }];
    
    
}


#pragma mark - 简化
+ (nullable NSURLSessionDataTask *)requestWithRequestType:(HTTPSRequestType)type
                                                urlString:(nonnull NSString *)urlString
                                                paraments:(nullable id)paraments
                                            completeBlock:(nullable completeBlock)completeBlock
{
    switch (type) {
        case HTTPSRequestTypeGet:
        {
            return  [BMHHTTPSession GET:urlString
                              paraments:paraments
                          completeBlock:^(NSDictionary * _Nullable object, NSError * _Nullable error) {
                              
                              completeBlock(object,error);
                          }];
        }
        case HTTPSRequestTypePost:
            return [BMHHTTPSession POST:urlString
                              paraments:paraments
                          completeBlock:^(NSDictionary * _Nullable object, NSError * _Nullable error) {
                              completeBlock(object,error);
                          }];
    }
    
}




#pragma mark - 加载图片
+ (void)downloadImage:(nonnull NSString *)url completed:(nullable DownloadImgCompletedBlock)completed imageView:(nullable UIImageView *)imageView
{
    [imageView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (completed != nil)
            completed(image);
        
    }];
    
}

#pragma mark -  取消所有的网络请求

/**
 *  取消所有的网络请求
 *  a finished (or canceled) operation is still given a chance to execute its completion block before it iremoved from the queue.
 */

+(void)cancelAllRequest
{
    [[BMHAppClient sharedClient].operationQueue cancelAllOperations];
}

#pragma mark -   取消指定的url请求/
/**
 *  取消指定的url请求
 *
 *  @param requestType 该请求的请求类型
 *  @param string      该请求的完整url
 */

+(void)cancelHttpRequestWithRequestType:(NSString *)requestType
                       requestUrlString:(NSString *)string
{
    NSError * error;
    /**根据请求的类型 以及 请求的url创建一个NSMutableURLRequest---通过该url去匹配请求队列中是否有该url,如果有的话 那么就取消该请求*/
    NSString * urlToPeCanced = [[[[BMHAppClient sharedClient].requestSerializer
                                  requestWithMethod:requestType URLString:string parameters:nil error:&error] URL] path];
    
    for (NSOperation * operation in [BMHAppClient sharedClient].operationQueue.operations) {
        //如果是请求队列
        if ([operation isKindOfClass:[NSURLSessionTask class]]) {
            //请求的类型匹配
            BOOL hasMatchRequestType = [requestType isEqualToString:[[(NSURLSessionTask *)operation currentRequest] HTTPMethod]];
            //请求的url匹配
            BOOL hasMatchRequestUrlString = [urlToPeCanced isEqualToString:[[[(NSURLSessionTask *)operation currentRequest] URL] path]];
            //两项都匹配的话  取消该请求
            if (hasMatchRequestType&&hasMatchRequestUrlString) {
                [operation cancel];
            }
        }
    }
}


- (void)AFNetworkStatus
{
    
    //1.创建网络监测者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    /*枚举里面四个状态  分别对应 未知 无网络 数据 WiFi
     typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
     AFNetworkReachabilityStatusUnknown          = -1,      未知
     AFNetworkReachabilityStatusNotReachable     = 0,       无网络
     AFNetworkReachabilityStatusReachableViaWWAN = 1,       蜂窝数据网络
     AFNetworkReachabilityStatusReachableViaWiFi = 2,       WiFi
     };
     */
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //这里是监测到网络改变的block  可以写成switch方便
        //在里面可以随便写事件
        NSLog(@"====网络状态====%ld",(long)status);
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络状态");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                networkReachabilityStatusUnknown();
                            break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据网");
                networkReachabilityStatusReachableViaWWAN();
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi网络");
                
                break;
                
            default:
                break;
        }
        
    }] ;
    
    /** 1. 开启监听 */
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}



void networkReachabilityStatusUnknown()
{
    
    
    
    
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"已为”直播“关闭蜂窝移动数据"
                                                                   message:@"您可以在”设置“中为此应用程序打开蜂窝移动数据。"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
                                                
                                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                                            }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"好"
                                              style:UIAlertActionStyleCancel handler:nil]];
    
    
    
    //[ presentViewController:alert animated:YES completion:nil];
    
    
}

void networkReachabilityStatusReachableViaWWAN()
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"“直播”正在使用流量，确定要如此土豪吗？"
                                                                   message:@"建议开启WIFI后观看视频。"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"设置"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action) {
                                                
                                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                                            }]];
    
    
    [alert addAction:[UIAlertAction actionWithTitle:@"好"
                                              style:UIAlertActionStyleCancel handler:nil]];
}


@end
